<template>
  <d2-container>
    <template slot="header" class="query-area">
      <el-form ref="queryForm" :model="queryForm" label-width="100px" style="height:auto">
        <template>
          <el-row class="query-row">
            <el-col :span="5">
               <el-form-item label="商品名称" prop="productName">
                  <el-input type="text" v-model="queryForm.productName" placeholder="请输入商品名称"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="5">
               <el-form-item label="商品编码" prop="productCode">
                  <el-input type="text" v-model="queryForm.productCode" placeholder="请输入商品编码"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="6">
						<el-form-item label="创建时间" prop="time">
							<el-date-picker
									v-model="time"
									type="datetimerange"
									:picker-options="pickerOptions"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="timestamp"
									align="right"
									:default-time="['00:00:00', '23:59:59']"
								></el-date-picker>
						</el-form-item>
					  </el-col>
            <el-col :span="4">
               <el-form-item>
                  <el-button type="primary" size="medium" @click="submitForm('queryForm')">查询</el-button>
                  <el-button type="primary" size="medium" @click="resetForm('queryForm')">重置</el-button></el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </template>
    <template>
      <template slot="header" class="query-area">
        <el-form label-width="140px" style="height: 50px">
          <el-button
            type="primary"
            @click="showProductPage()"
            style="margin-left: 20px"
            >添加关联商品</el-button>
        </el-form>
      </template>
      <div class="form-table">
        <el-table :data="tableData" stripe border style="width: 100%">
          <el-table-column
             type="index"
            label="序号"
            width="50"
          ></el-table-column>
          <el-table-column
            v-if="false"
            prop="supplierId"
            label="供应商id"
          ></el-table-column>
          <el-table-column
            v-if="false"
            prop="productId"
            label="商品id"
          ></el-table-column>
          <el-table-column
            prop="supplierName"
            label="供应商名称"
          ></el-table-column>
          <el-table-column
            prop="productName"
            label="商品名称"
          ></el-table-column>
          <el-table-column
            prop="productCode"
            label="商品编码"
          ></el-table-column>
          <el-table-column prop="status" label="上架状态" width="80">
            <template slot-scope="scope">
              {{ scope.row.status == 0 ? "下架" : "上架" }}
            </template>
          </el-table-column>
          <el-table-column prop="supplyArea" label="供货区域">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.supplyArea }}</span>
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.supplyArea"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="setNum" label="起订数量">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.setNum }}</span>
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.setNum"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="referenceSupplyPrice" label="参考供货价(元)">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{
                scope.row.referenceSupplyPrice
              }}</span>
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.referenceSupplyPrice"
                clearable
              ></el-input> </template
          ></el-table-column>
          <el-table-column prop="deliveryPlace" label="发货地">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{
                scope.row.deliveryPlace
              }}</span>
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.deliveryPlace"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="freightIsOwn" label="运费是否自理">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{
                scope.row.freightIsOwn == 0 ? "否" : "是"
              }}</span>
              <el-select
                v-if="scope.row.isEdit"
                v-model="scope.row.freightIsOwn"
              >
                <el-option value="0" label="否">否</el-option>
                <el-option value="1" label="是">是</el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="deliveryCycle" label="发货周期">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{
                scope.row.deliveryCycle
              }}</span>
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.deliveryCycle"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="settlementPeriod" label="结算账期">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{
                scope.row.settlementPeriod
              }}</span>
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.settlementPeriod"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" :formatter="forDateCreate" width="150"></el-table-column>
          <el-table-column prop="reviseTime" label="修改时间" :formatter="forDateRevise" width="150"></el-table-column>
          <el-table-column label="操作" fixed="right" width="145">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                plain
                v-if="!scope.row.isEdit"
                @click="scope.row.isEdit = true"
                >编辑</el-button
              >
              <el-button
                type="primary"
                size="small"
                v-if="scope.row.isEdit"
                @click="editSaveRow(scope.row)"
                >保存</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="deleteRow(scope.$index, scope.row)"
                plain
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
    <!-- 页脚部分 -->
		<template slot="footer">
			<div class="page">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</template>

    <!-- 弹框-添加关联商品 -->
    <template>
      <el-dialog title="添加关联商品" width="60%" :visible.sync="showProductList">
        <div class="dialog-search">
          <el-form class="inline-form" :inline="true" ref="searchForm" :model="searchForm">
            <el-form-item label="商品名称">
              <el-input
                v-model="searchForm.productName"
                placeholder="请输入商品名称"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品编码">
              <el-input
                v-model="searchForm.productCode"
                placeholder="请输入商品编码"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-button type="primary" size="medium" @click="submitFormProduct('searchForm')">搜索</el-button>
          </el-form>
        </div>
        <div class="form-table">
          <el-table :data="tableDataProduct" stripe border style="width: 100%">
            <el-table-column label="序号" type="index" width="50"></el-table-column>
            <el-table-column property="productName" label="商品名称"></el-table-column>
            <el-table-column property="productCode" label="商品编号"></el-table-column>
            <el-table-column prop="status" label="商品状态">
              <template slot-scope="scope">
                {{scope.row.status==0?"下架":"上架"}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  disabled
                  v-if="scope.row.choice != 0"
                  >已选</el-button
                >
                <el-button
                  type="primary"
                  plain
                  size="small"
                  v-if="scope.row.choice==0 && !scope.row.isSeleted"
                  @click="scope.row.isSeleted = true"
                  >选择</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  v-if="scope.row.choice==0 && scope.row.isSeleted"
                  @click="scope.row.isSeleted = false"
                  >已选</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page dialog-page">
          <el-pagination
            background
            @current-change="handleCurrentChangeProduct"
            :current-page="currentPageProduct"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSizeProduct"
            layout="total, prev, pager, next"
            :total="totalProduct"
          ></el-pagination>
        </div>
        <div class="dialog-footer" slot="footer">
          <el-button type="primary" @click="saveRelation">保存</el-button>
          <el-button @click="showProductList = false">取消</el-button>
        </div>
      </el-dialog>
    </template>
  </d2-container>
</template>
<script>
import {
  findAllSupplierProductListByPage,
  addBatchSupplierProductByProductIds,
  editSaveSupplierProduct,
  deleteSupplierProduct
} from '@api/supplier/supplier'
import {
  findProductInfoListByPage
} from '@api/product/product'
import dayjs from 'dayjs'
export default {
  name: 'supplier-supplierProductList',
  components: {},
  data () {
    return {
      supplierUpdateId: '',
      queryForm: {
        productName: '',
        productCode: '',
        startTime: '',
        endTime: ''
      },
      time: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,

      showProductList: false,
      searchForm: {
        productName: '',
        productCode: ''
      },
      tableDataProduct: [],
      currentPageProduct: 1,
      pageSizeProduct: 10,
      totalProduct: 0,
      productIds: ''
    }
  },
  created () {
    this.supplierUpdateId = sessionStorage.getItem('supplierId')
  },
  mounted () {
    this.fetchData()
  },
  watch: {
  },
  methods: {
    fetchData () {
      this.loading = true
      this.queryForm.startTime = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss')
      this.queryForm.endTime = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss')
      findAllSupplierProductListByPage({
        supplierId: this.supplierUpdateId,
        productName: this.queryForm.productName,
        productCode: this.queryForm.productCode,
        startTime: this.queryForm.startTime,
        endTime: this.queryForm.endTime,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
        .then((res) => {
          for (let index in res.data.content) {
            res.data.content[index].isEdit = false
            res.data.content[index].freightIsOwn += ''
          }
          this.tableData = res.data.content
          this.loading = false
        })
        .catch((err) => {
          console.log('err', err)
          this.loading = false
        })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.fetchData()
    },
    resetPage () {
        this.currentPage = 1,
        this.pageSize = 10,
        this.total = 0
    },
    submitForm (formName) {
      this.resetPage()
      this.fetchData()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.time = []
      this.resetPage()
      this.fetchData()
    },
    forDateCreate (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    forDateRevise (row, column) {
      return row.reviseTime == null
        ? ''
        : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss')
    },
    editSaveRow (row) {
      this.$confirm('确认修改数据吗？').then((_) => {
        this.loading = true
        if (row.setNum === '') {
          this.$message({ message: '起订数量不能为空', type: 'error' })
          return
        }
        if (isNaN(row.setNum)) {
          this.$message({ message: '起订数量必须为数值类型', type: 'error' })
          return
        }
        if (Math.floor(parseFloat(row.setNum)) !== parseFloat(row.setNum)) {
          this.$message({ message: '起订数量必须为整数', type: 'error' })
          return
        }
        if (row.referenceSupplyPrice === '') {
          this.$message({ message: '参考价格不能为空', type: 'error' })
          return
        }
        if (isNaN(row.referenceSupplyPrice)) {
          this.$message({ message: '参考价格必须为数值类型', type: 'error' })
          return
        }
        if (row.deliveryCycle === '') {
          this.$message({ message: '发货周期不能为空', type: 'error' })
          return
        }
        if (isNaN(row.deliveryCycle)) {
          this.$message({ message: '发货周期必须为数值类型', type: 'error' })
          return
        }
        if (Math.floor(parseFloat(row.deliveryCycle)) !== parseFloat(row.deliveryCycle)) {
          this.$message({ message: '发货周期必须为整数', type: 'error' })
          return
        }
        if (row.settlementPeriod === '') {
          this.$message({ message: '结算账期不能为空', type: 'error' })
          return
        }
        if (isNaN(row.settlementPeriod)) {
          this.$message({ message: '结算账期必须为数值类型', type: 'error' })
          return
        }
        if (Math.floor(parseFloat(row.settlementPeriod)) !== parseFloat(row.settlementPeriod)) {
          this.$message({ message: '结算账期必须为整数', type: 'error' })
          return
        }
        editSaveSupplierProduct({
          supplierId: row.supplierId,
          productId: row.productId,
          supplyArea: row.supplyArea,
          setNum: row.setNum,
          referenceSupplyPrice: row.referenceSupplyPrice,
          deliveryPlace: row.deliveryPlace,
          freightIsOwn: row.freightIsOwn,
          deliveryCycle: row.deliveryCycle,
          settlementPeriod: row.settlementPeriod
        })
          .then((res) => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              row.isEdit = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch((err) => {
            console.log('err', err)
          })
      })
    },
    deleteRow (index, row) {
      this.$confirm('确认删除【' + row.productName + '】的关联关系吗？').then(
        (_) => {
          this.loading = true
          deleteSupplierProduct({
            supplierId: this.supplierUpdateId,
            productId: row.id
          })
            .then((res) => {
              var code = res.code
              if (res.code == '000000') {
                this.$message({ message: res.message, type: 'success' })
                this.fetchData()
                this.loading = false
              } else {
                this.$message({ message: res.message, type: 'error' })
              }
            })
            .catch((err) => {
              console.log('err', err)
              this.loading = false
            })
        }
      )
    },

    showProductPage () {
      this.fetchDataProduct()
      this.showProductList = true
    },
    fetchDataProduct () {
      findProductInfoListByPage({
        supplierId: this.supplierUpdateId,
        productName: this.searchForm.productName,
        productCode: this.searchForm.productCode,
        currentPage: this.currentPageProduct,
        pageSize: this.pageSizeProduct
      })
        .then((res) => {
          for (let index in res.data.content) {
            res.data.content[index].isSeleted = false
          }
          this.tableDataProduct = res.data.content
          this.totalProduct = res.data.total
          this.loading = false
        })
        .catch((err) => {
          console.log('err', err)
          this.loading = false
        })
    },
    handleSizeChangeProduct (val) {
      this.pageSizeProduct = val
      this.fetchDataProduct()
    },
    handleCurrentChangeProduct (val) {
      this.currentPageProduct = val
      this.fetchDataProduct()
    },
    resetPageProduct () {
        this.currentPageProduct  = 1,
        this.pageSizeProduct  = 10,
        this.totalProduct  = 0
    },
    submitFormProduct (formName) {
      this.resetPageProduct()
      this.fetchDataProduct()
    },
    saveRelation () {
      var idsStr = ''
      this.tableDataProduct.forEach(row => {
        if (row.isSeleted == true) {
          idsStr += ',' + row.id
        }
      })
      if(idsStr == ',undefined' || idsStr == '') {
        this.$message({ message: '请先选择商品', type: 'warning' })
        return
      }
      idsStr = idsStr.slice(1)
      addBatchSupplierProductByProductIds({
        supplierId: this.supplierUpdateId,
        productIds: idsStr
      })
        .then((res) => {
          var code = res.code
          if (res.code == '000000') {
            this.$message({ message: res.message, type: 'success' })
            this.fetchData()
            this.fetchDataProduct()
            this.showProductList = false
          } else {
            this.$message({ message: res.message, type: 'error' })
            this.showProductList = false
          }
        })
        .catch((err) => {
          console.log('err', err)
        })
    }
  }
}
</script>
